package cn.iocoder.yudao.module.iot.util;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.iot.controller.admin.deviceeventslog.vo.DeviceEventsLogCreateReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.phonemsglog.vo.PhoneMsgLogSaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.devicerel.DeviceRelDO;
import cn.iocoder.yudao.module.iot.dal.dataobject.warnpolicy.WarnPolicyDO;
import cn.iocoder.yudao.module.iot.enums.Channel;
import cn.iocoder.yudao.module.iot.mq.Producer;
import cn.iocoder.yudao.module.iot.service.deviceeventslog.DeviceEventsLogService;
import cn.iocoder.yudao.module.iot.service.devicerel.DeviceRelService;
import cn.iocoder.yudao.module.iot.service.phonemsglog.PhoneMsgLogService;
import cn.iocoder.yudao.module.iot.service.warnpolicy.WarnPolicyService;
import cn.iocoder.yudao.module.iot.vo.DeviceRepsonseVo;
import cn.iocoder.yudao.module.iot.vo.DeviceStatusVo;
import cn.iocoder.yudao.module.system.api.sms.SmsSendApi;
import cn.iocoder.yudao.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.qpid.jms.JmsConnection;
import org.apache.qpid.jms.JmsConnectionListener;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.net.InetAddress;
import java.net.URI;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.core.env.Environment;

@Component
public class AmqpClientUtil {

    @Autowired
    private Producer producer;

    @Resource
    private DeviceEventsLogService deviceEventsLogService;

    @Resource
    private PhoneMsgLogService phoneMsgLogService;

    @Resource
    private DeviceRelService deviceRelService;

    @Resource
    private WarnPolicyService warnPolicyService;


    @Autowired
    private Environment environment;

    @Resource
    private SmsSendApi smsSendApi;


    private final static Logger logger = LoggerFactory.getLogger(AmqpClientUtil.class);
    /**
     * 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考
     */
    @Value("${iot.accessKey}")
    private String accessKey;
    @Value("${iot.accessSecret}")
    private String accessSecret;
    @Value("${iot.consumerGroupId}")
    private String consumerGroupId;
    //iotInstanceId：实例ID。若是2021年07月30日之前（不含当日）开通的公共实例，请填空字符串。
    @Value("${iot.iotInstanceId}")
    private String iotInstanceId;
    //${YourHost}为接入域名，请参见AMQP客户端接入说明文档。
    @Value("${iot.host}")
    private String host;


    // 指定单个进程启动的连接数
    // 单个连接消费速率有限，请参考使用限制，最大64个连接
    // 连接数和消费速率及rebalance相关，建议每500QPS增加一个连接
    private static int connectionCount = 4;

    //业务处理异步线程池，线程池参数可以根据您的业务特点调整，或者您也可以用其他异步方式处理接收到的消息。
    private final static ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue(50000));

    @PostConstruct
    public void getMsg() throws Exception {
        // 判断运行环境，本地环境不启动消息监听

        String[] activeProfiles = environment.getActiveProfiles();

        if(activeProfiles.length>0){
            String activeProfile = activeProfiles[0];
            if("local".equals(activeProfile)){
                logger.info("---------------local环境不启动iot消息监听-------------");
                return;
            }
        }
        logger.info("启动了getMsg方法");
        List<Connection> connections = new ArrayList<>();
        Map<String, String> getenv = System.getenv();
        //参数说明，请参见AMQP客户端接入说明文档。
        for (int i = 0; i < connectionCount; i++) {
            long timeStamp = System.currentTimeMillis();
            //签名方法：支持hmacmd5、hmacsha1和hmacsha256。
            String signMethod = "hmacsha1";
            InetAddress address = InetAddress.getLocalHost();
            String clientId=address.getHostAddress(); // 使用ip作为消费端唯一标识
            //userName组装方法，请参见AMQP客户端接入说明文档。
            String userName = clientId + "-" + i + "|authMode=aksign"
                    + ",signMethod=" + signMethod
                    + ",timestamp=" + timeStamp
                    + ",authId=" + accessKey
                    + ",iotInstanceId=" + iotInstanceId
                    + ",consumerGroupId=" + consumerGroupId
                    + "|";
            //计算签名，password组装方法，请参见AMQP客户端接入说明文档。
            String signContent = "authId=" + accessKey + "&timestamp=" + timeStamp;
            String password = doSign(signContent, accessSecret, signMethod);
            String connectionUrl = "failover:(amqps://" + host + ":5671?amqp.idleTimeout=80000)"
                    + "?failover.reconnectDelay=30";

            Hashtable<String, String> hashtable = new Hashtable<>();
            hashtable.put("connectionfactory.SBCF", connectionUrl);
            hashtable.put("queue.QUEUE", "default");
            hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
            Context context = new InitialContext(hashtable);
            ConnectionFactory cf = (ConnectionFactory)context.lookup("SBCF");
            Destination queue = (Destination)context.lookup("QUEUE");
            // 创建连接。
            Connection connection = cf.createConnection(userName, password);
            connections.add(connection);

            ((JmsConnection)connection).addConnectionListener(myJmsConnectionListener);
            // 创建会话。
            // Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()。
            // Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）。
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            connection.start();
            // 创建Receiver连接。
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(messageListener);
        }

        logger.info("amqp demo is started successfully with springboot!");
    }

    private MessageListener messageListener = new MessageListener() {
        @Override
        public void onMessage(final Message message) {
            try {
                //1.收到消息之后一定要ACK。
                // 推荐做法：创建Session选择Session.AUTO_ACKNOWLEDGE，这里会自动ACK。
                // 其他做法：创建Session选择Session.CLIENT_ACKNOWLEDGE，这里一定要调message.acknowledge()来ACK。
                // message.acknowledge();
                //2.建议异步处理收到的消息，确保onMessage函数里没有耗时逻辑。
                // 如果业务处理耗时过程过长阻塞住线程，可能会影响SDK收到消息后的正常回调。
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        processMessage(message);
                    }
                });
            } catch (Exception e) {
                logger.error("submit task occurs exception ", e);
            }
        }
    };


    /**
     * 在这里处理您收到消息后的具体业务逻辑。
     */
    private void processMessage(Message message) {
        Jedis jr = null;
        try {
            byte[] body = message.getBody(byte[].class);
            String content = new String(body);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            logger.info("接收到设备端消息："
                    + ",\n topic = " + topic
                    + ",\n messageId = " + messageId
                    + ",\n content = " + content);
            String devTop="user/deviceUpload";
            String statusTop="mqtt/status";
            String templateCode="SMS_463895057";
            // 设备上线/离线
            if(!StringUtils.isEmpty(topic)&&topic.contains(statusTop)){ //设备上线/离线
                if(!StringUtils.isEmpty(content)){
                    // 创建ObjectMapper对象
                    ObjectMapper objectMapper = new ObjectMapper();
                    // 解析JSON字符串为Java对象
                    DeviceStatusVo response = objectMapper.readValue(content, DeviceStatusVo.class);
                    logger.info("deviceOnOffline--开始发送消息--start");
                    String deviceName = response.getDeviceName();
                    producer.publishMessage(Channel.DEVICE_STATUS_ONOFFLINE_CHANNEL+deviceName,content);
                    logger.info("deviceOnOffline--开始发送完成--end");
                    DeviceEventsLogCreateReqVO createReqVO=new DeviceEventsLogCreateReqVO();
                    LocalDateTime time = LocalDateTime.now();
                    String status = response.getStatus();
                    String desc="";
                    if("online".equals(status)){
                        desc="设备上线";
                    }else if("offline".equals(status)){
                        desc="设备下线";
                    }
                    createReqVO.setTime(time);
                    createReqVO.setAction(status);
                    createReqVO.setDeviceName(deviceName);
                    createReqVO.setDescription(desc);
                    createReqVO.setDeviceData(content);
                    deviceEventsLogService.createDeviceEventsLog(createReqVO);
                    String type="状态";
                    String warnType="状态";
                    String value=desc;
                    sendNotice(deviceName,templateCode,warnType,type,value,"7");
                }
            }
            if(!StringUtils.isEmpty(topic)&&topic.contains(devTop)){
                if(!StringUtils.isEmpty(content)){
                    // 创建ObjectMapper对象
                    ObjectMapper objectMapper = new ObjectMapper();
                    // 解析JSON字符串为Java对象
                    DeviceRepsonseVo response = objectMapper.readValue(content, DeviceRepsonseVo.class);
                    String id = response.getId();
                    String deviceName = response.getParams().getDeviceName();
                    DeviceEventsLogCreateReqVO createReqVO=new DeviceEventsLogCreateReqVO();
                    LocalDateTime time = LocalDateTime.now();
                    createReqVO.setTime(time);
                    createReqVO.setAction("uploadDeviceStatus");
                    createReqVO.setDeviceName(deviceName);
                    String desc="";
                    String action="";
                    if("uploadDeviceStatus".equals(response.getMethod())){ // 召读上报
                        logger.info("uploadDeviceStatus--开始发送消息--start");
                        producer.publishMessage(Channel.UPLOAD_DEVICE_STATUS_CHANNEL+id,content);
                        logger.info("uploadDeviceStatus--开始发送完成--end");
                        action="uploadDeviceStatus";
                        desc="设备召读上报状态";
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                    }else if("uploadDeviceStatusOnline".equals(response.getMethod())){ // 开机上报
                        logger.info("uploadDeviceStatusOnline--开始发送消息--start");
                        producer.publishMessage(Channel.UPLOAD_DEVICE_STATUS_CHANNEL+id,content);
                        logger.info("uploadDeviceStatusOnline--开始发送完成--end");
                        action="uploadDeviceStatusOnline";
                        desc="设备开机上报状态";
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                    }else if("calibration".equals(response.getMethod())){ // 数据标定
                        logger.info("calibration--开始发送消息--start");
                        producer.publishMessage(Channel.DEVICE_BIAODING_CHANNEL+id,content);
                        logger.info("calibration--开始发送完成--end");
                        String biaoding = response.getParams().getBiaoding();
                        action="calibration";
                        switch (biaoding){
                            case "b111":
                                desc="设备进入标定模式";
                                break;
                            case "b222":
                                desc="设备退出标定模式";
                                break;
                            case "b333":
                                desc="设备标定失败";
                                break;
                            case "b000":
                                desc="设备0%标定";
                                break;
                            case "b020":
                                desc="设备20%标定";
                                break;
                            case "b030":
                                desc="设备30%标定";
                                break;
                            case "b040":
                                desc="设备40%标定";
                                break;
                            case "b050":
                                desc="设备50%标定";
                                break;
                            case "b060":
                                desc="设备60%标定";
                                break;
                        }
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                    } else if("uploadDeviceWarn".equals(response.getMethod())){ // 温度浓度报警
                        logger.info("uploadDeviceWarn--开始发送消息--start");
                        producer.publishMessage(Channel.UPLOAD_DEVICE_WARN+deviceName,content);
                        logger.info("uploadDeviceWarn--开始发送完成--end");
                        String warnType = response.getParams().getWarnType();
                        action="uploadDeviceWarn";
                        String wd = response.getParams().getWd();
                        String rd = response.getParams().getRd();
                        String type="";
                        String value="";
                        if("1".equals(warnType)){ // 温度报警
                            desc="设备温度异常报警，当前设备温度:"+wd+"度";
                            type="温度";
                            value=wd+"度";
                            createReqVO.setTime(time);
                            createReqVO.setAction(response.getMethod());
                            createReqVO.setDeviceName(deviceName);
                            createReqVO.setDescription(desc);
                            createReqVO.setDeviceData(content);
                            deviceEventsLogService.createDeviceEventsLog(createReqVO);
                            sendNotice(deviceName,templateCode,type,type,value,"1");
                        }else if("2".equals(warnType)){
                            desc="设备浓度异常报警，当前设备浓度:"+rd+"LEL";
                            type="浓度";
                            value=rd+"LEL";
                            createReqVO.setTime(time);
                            createReqVO.setAction(response.getMethod());
                            createReqVO.setDeviceName(deviceName);
                            createReqVO.setDescription(desc);
                            createReqVO.setDeviceData(content);
                            deviceEventsLogService.createDeviceEventsLog(createReqVO);
                            sendNotice(deviceName,templateCode,type,type,value,"2");
                        }
                    } else if("changeZt".equals(response.getMethod())){ // 打开或关闭排气阀
                        logger.info("changeZt--开始发送消息--start");
                        producer.publishMessage(Channel.DEVICE_ZT_CHANGE_CHANNEL+id,content);
                        logger.info("changeZt--开始发送完成--end");
                        action="changeZt";
                        String pqzt = response.getParams().getPqzt();
                        String qfzt = response.getParams().getQfzt();
                        String qfztDesc="0".equals(qfzt)?"气阀关闭,":"气阀开启,";
                        String pqztDesc="0".equals(pqzt)?"排风扇关闭,":"排风扇开启";
                        desc=qfztDesc+pqztDesc;
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                    }else if("uploadDeviceWarnCancel".equals(response.getMethod())){ // 设备温度报警解除
                        logger.info("uploadDeviceWarnCancel--开始发送消息--start");
                        producer.publishMessage(Channel.UPLOAD_DEVICE_WARN_CANCEL+deviceName,content);
                        logger.info("uploadDeviceWarnCancel--开始发送完成--end");
                        String warnType = response.getParams().getWarnType();
                        action="uploadDeviceWarnCancel";
                        String wd = response.getParams().getWd();
                        String rd = response.getParams().getRd();
                        String value="";
                        String type="";
                        if("1".equals(warnType)){ // 温度报警解除
                            desc="温度异常报警已解除，当前设备温度:"+wd+"度";
                            value=wd+"度";
                            type="温度";
                        }else if("2".equals(warnType)){ // 浓度报警解除
                            desc="浓度异常报警已解除，当前设备浓度:"+rd+"LEL";
                            value=rd+"LEL";
                            type="浓度";
                        }else if("3".equals(warnType)){ //同时解除
                            desc="温度和浓度异常报警已解除，当前设备温度:"+wd+"度，浓度:"+rd+"LEL";
                            type="温度浓度";
                        }
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                        sendNotice(deviceName,templateCode,type,"状态为",desc,"8");
                    }else if("deviceElecChange".equals(response.getMethod())){ // 市电状态变化
                        logger.info("deviceElecChange--开始发送消息--start");
                        producer.publishMessage(Channel.ELEC_CHANGE_CHANNEL+deviceName,content);
                        logger.info("deviceElecChange--开始发送完成--end");
                        action="deviceElecChange";
                        String sdno = response.getParams().getSdno();
                        String sdnoDesc="1".equals(sdno)?"已恢复":"已断开";
                        desc="设备市电异常，当前市电状态"+sdnoDesc;
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                        sendNotice(deviceName,templateCode,"市电","市电状态为",sdnoDesc,"4");
                    }else if("deviceBatChange".equals(response.getMethod())){ // 电池状态变化
                        logger.info("deviceBatChange--开始发送消息--start");
                        producer.publishMessage(Channel.BAT_CHANGE_CHANNEL+deviceName,content);
                        logger.info("deviceBatChange--开始发送完成--end");
                        action="deviceBatChange";
                        String bclpEr = response.getParams().getBclpEr();
                        String dcDesc="0".equals(bclpEr)?"电压恢复正常":"低电压";
                        desc="设备电池异常，当前电池"+dcDesc;
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                        sendNotice(deviceName,templateCode,"电池","电池状态",dcDesc,"3");
                    }else if("deviceUsingChange".equals(response.getMethod())){ // 阀门拆卸报警
                        logger.info("deviceUsingChange--开始发送消息--start");
                        producer.publishMessage(Channel.DEVICE_USING_CHANGE+deviceName,content);
                        logger.info("deviceUsingChange--开始发送完成--end");
                        action="deviceUsingChange";
                        String using = response.getParams().getUsing();
                        String qfzt = response.getParams().getQfzt();
                        String value="";
                        if("2".equals(using)){// 已拆卸
                            desc="设备状态变化，当前设备状态为已拆卸";
                            value="已拆卸";
                        }else if("1".equals(using)){
                            desc="设备状态变化，当前设备状态为已安装";
                            value="已安装";
                        } else if("0".equals(using)){
                            desc="设备状态变化，当前设备状态为已安装";
                            value="已安装";
                        }
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                        sendNotice(deviceName,templateCode,"状态","安装状态",value,"5");
                    } else if("deviceFanChange".equals(response.getMethod())){ // 预报警风扇开启
                        logger.info("deviceFanChange--开始发送消息--start");
                        producer.publishMessage(Channel.DEVICE_FAN_CHANGE+deviceName,content);
                        logger.info("deviceFanChange--开始发送完成--end");
                        action="deviceFanChange";
                        desc="设备浓度预警，排风扇已开启";
                        String warnType="浓度异常";
                        String de="浓度超标，排风扇已开启";
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                        sendNotice(deviceName,templateCode,"燃气浓度","燃气",de,"6");
                    }else if("getLocation".equals(response.getMethod())){ // 召读获取设备定位
                        logger.info("getLocation--开始发送消息--start");
                        producer.publishMessage(Channel.UPLOAD_DEVICE_LOCATION_CHANNEL+id,content);
                        logger.info("getLocation--开始发送完成--end");
                        desc="设备召读上报定位信息";
                        createReqVO.setTime(time);
                        createReqVO.setAction(response.getMethod());
                        createReqVO.setDeviceName(deviceName);
                        createReqVO.setDescription(desc);
                        createReqVO.setDeviceData(content);
                        deviceEventsLogService.createDeviceEventsLog(createReqVO);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("processMessage occurs error ", e);
        }finally {
            if(jr!=null){
                jr.disconnect();

            }
        }
    }

    private void sendNotice(String deviceName, String templateCode,
                         String warnType,String type,String value,String eventType) {
        LocalDateTime now = LocalDateTime.now();
        Map code=new HashMap();
        DeviceRelDO rel = deviceRelService.getDeviceRelByDeviceName(deviceName);
        if(rel!=null&&!StringUtils.isEmpty(rel.getNoticeType())){
            String noticeType = rel.getNoticeType();
            if(!StringUtils.isEmpty(noticeType)&&noticeType.contains(eventType)){
                List<WarnPolicyDO> policyList = warnPolicyService.getWarnPolicyList(deviceName);
                for(WarnPolicyDO ploicy:policyList){
                    String phoneNum = ploicy.getPhone();
                    String noticeWay = ploicy.getNoticeWay();
                    boolean cellPhone = PhoneUtils.isCellPhone(phoneNum);
                    if(cellPhone&&!StringUtils.isEmpty(noticeWay)&&noticeWay.contains("1")){// 短信
                        //短信
                        code.put("warnType",warnType);
                        code.put("type",type);
                        code.put("value", value);
                        boolean send = SmsUtil.send(phoneNum, templateCode, code);
/*                        SmsSendSingleToUserReqDTO user=new SmsSendSingleToUserReqDTO();
                        user.setUserId(ploicy.getId());
                        smsSendApi.sendSingleSmsToMember(user);*/
                        PhoneMsgLogSaveReqVO phoneMsg=new PhoneMsgLogSaveReqVO();
                        phoneMsg.setPhone(phoneNum);
                        phoneMsg.setDeviceName(deviceName);
                        phoneMsg.setSendType(true);
                        phoneMsg.setSendTime(now);
                        phoneMsg.setContentValue(JsonUtils.toJsonString(code));
                        phoneMsg.setTempCode(templateCode);
                        String msgContent="【晨灵科技】您好，您的燃气报警器出现状态异常报警,当前设备状态为"+ value +"请您注意用气安全！";
                        phoneMsg.setContent(msgContent);
                        phoneMsg.setPhoneUser(String.valueOf(rel.getMemberId()));
                        phoneMsgLogService.createPhoneMsgLog(phoneMsg);
                        logger.info("发送短信报警信息，"+ JSONObject.toJSONString(code));
                    }
                    if(!StringUtils.isEmpty(noticeWay)&&noticeWay.contains("0")){ //电话
                        Map callMsg=new HashMap();
                        callMsg.put("warnType",warnType);
                        callMsg.put("value",warnType+"为"+value);
                        String msg=JSONObject.toJSONString(callMsg);
                        try {
                            SingleCallByTts.call(phoneNum,msg);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        PhoneMsgLogSaveReqVO phoneMsg=new PhoneMsgLogSaveReqVO();
                        phoneMsg.setPhone(phoneNum);
                        phoneMsg.setDeviceName(deviceName);
                        phoneMsg.setSendType(false);// 电话通知方式
                        phoneMsg.setSendTime(now);
                        phoneMsg.setContentValue(JsonUtils.toJsonString(callMsg));
                        phoneMsg.setTempCode("TTS_287045128");
                        String msgContent="【晨灵科技】您好，您的燃气报警器出现状态异常报警,当前设备状态为"+ value +"请您注意用气安全！";
                        phoneMsg.setContent(msgContent);
                        phoneMsg.setPhoneUser(String.valueOf(rel.getMemberId()));
                        phoneMsgLogService.createPhoneMsgLog(phoneMsg);
                        logger.info("拨打报警电话信息，"+ JSONObject.toJSONString(code));
                    }
                }
            }
        }
    }


    private static JmsConnectionListener myJmsConnectionListener = new JmsConnectionListener() {
        /**
         * 连接成功建立。
         */
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            logger.info("onConnectionEstablished, remoteUri:{}", remoteURI);
        }

        /**
         * 尝试过最大重试次数之后，最终连接失败。
         */
        @Override
        public void onConnectionFailure(Throwable error) {
            logger.error("onConnectionFailure, {}", error.getMessage());
        }

        /**
         * 连接中断。
         */
        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            logger.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
        }

        /**
         * 连接中断后又自动重连上。
         */
        @Override
        public void onConnectionRestored(URI remoteURI) {
            logger.info("onConnectionRestored, remoteUri:{}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {}

        @Override
        public void onSessionClosed(Session session, Throwable cause) {}

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {}

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {}
    };

    /**
     * 计算签名，password组装方法，请参见AMQP客户端接入说明文档。
     */
    private static String doSign(String toSignString, String secret, String signMethod) throws Exception {
        SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), signMethod);
        Mac mac = Mac.getInstance(signMethod);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(toSignString.getBytes());
        return Base64.encodeBase64String(rawHmac);
    }
}
